#encoding:utf-8
import json
import re
import datetime
import math
import socket
import struct

def check_bsonId(bsonId):
    '''
    check bsonId
    '''
    if not bsonId:
        return False
    reg = re.compile("^[0-9a-fA-F]{24}$")
    return reg.match(bsonId)


def get_avatar(filename=None, size=None, gender=None):
    if not filename:
        if not size:
            size = 128
        if not gender:
            gender = "unknow"
        return "/static/img/{0}-{1}.png".format(gender,size)

    else:
        return "/avatar/{0}".format(filename)

def format_date(tm, type_int):
        if not tm:
            return ''
        if type(tm) is unicode:
            tm = datetime.datetime.strptime(tm, "%Y-%m-%d %H:%M:%S.%f")
        if type_int == 1:
            return tm.strftime("%Y-%m-%d %H:%M:%S")
        if type_int == 2:
            return tm.strftime("%Y-%m-%d")
        else:
            return tm.strftime("%H:%M / %d-%m-%Y")

def convert_to_datetime(dtstring):
    return datetime.datetime.strptime(dtstring, "%Y-%m-%d %H:%M:%S.%f")

def timesince(dt):
    """
    Returns string representing "time since" e.g.
    3 days ago, 5 hours ago etc.
    """
    now = datetime.datetime.now()
    if type(dt) is unicode:
        dt = datetime.datetime.strptime(dt.replace('T', ' '), "%Y-%m-%d %H:%M:%S.%f")
    diff = now - dt

    years = diff.days / 365
    months = diff.days / 30
    weeks = diff.days / 7
    days = diff.days
    hours = diff.seconds / 3600
    minutes = diff.seconds / 60
    seconds = diff.seconds

    if years > 0:
        return u"{0}年前".format(years)
    if months > 0:
        return u"{0}个月前".format(months)
    if weeks > 0:
        return u"{0}周前".format(weeks)
    if days > 0:
        return u"{0}天前".format(days)
    if hours > 0:
        return u"{0}小时前".format(hours)
    if minutes > 0:
        return u"{0}分钟前".format(minutes)
    if seconds > 0:
        return u"{0}秒钟前".format(seconds)
    else:
         return u"刚才"


class Pagination(object):
    def __init__(self, record, per_page, page, per_page_num):
        self.record = record
        self.per_page = per_page
        self.page = page
        self.per_page_num = per_page_num


    @property
    def page_count(self):
        return math.trunc(math.ceil(self.record * 1.0 / self.per_page ))

    @property
    def page_num_lsit(self):
        num_max = math.trunc(math.ceil(self.page * 1.0 / self.per_page_num)) * self.per_page_num + 1
        num_min = num_max - self.per_page_num
        num_max = self.page_count + 1 if num_max > self.page_count + 1 else num_max
        return list(xrange(num_min, num_max))

def ip2long(ip):
    return struct.unpack("!I",socket.inet_aton(ip))[0]

def long2ip(num):
    return socket.inet_ntoa(struct.pack("!I",num))


def get_file_size(sourcefile):
    sourcefile.seek(0, 2)  # Seek to the end of the file
    size = sourcefile.tell()  # Get the position of EOF
    sourcefile.seek(0)  # Reset the file position to the beginning
    return size


def get_scroll_skip(page_size,scroll_size,page):
    '''
    滚动分页时获取 limit and skip
    '''
    skip = 0
    if page <= 1:
        skip = 0
    elif page == 2:
        skip = page_size
    else:
        skip = page_size + (page-2)*scroll_size
    page_size = page_size if page == 1 else scroll_size
    return (page_size,skip)


class Serializer:
    """
    列化json
    """
    @staticmethod
    def serialize(obj):
        return json.dumps(obj, cls=JSONEncoder)


class JSONEncoder(json.JSONEncoder):
    def default(self, obj):
        if hasattr(obj, 'isoformat'): #handles both date and datetime objects
            return obj.isoformat()
        else:
            return json.JSONEncoder.default(self, obj)
